﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MaxLeaf.Common;
using System.Data;
using MaxLeaf.DB;
using MySql.Data.MySqlClient;

namespace MaxLeaf.DAL.Web
{
    public class OeSalesOrderDAL 
    {

        private string mstrOrderHdr_K3 = new K3.OeSalesOrderDAL().mstrOEHDR_K3 ;
        private string mstrOrderHdr_Web = new K3.OeSalesOrderDAL().mstrOEHDR_Web;

        private string mstrOrderDtl_K3 = new K3.OeSalesOrderDAL().mstrOEDTL_K3;
        private string mstrOrderDtl_Web = new K3.OeSalesOrderDAL().mstrOEDTL_Web; 

        private string mstrFieldNamesHDR_K3 =new K3.OeSalesOrderDAL().mstrFieldNamesHDR_K3;
        private string mstrFieldNamesDTL_K3 =new K3.OeSalesOrderDAL().mstrFieldNamesDTL_K3;

        private string mstrFieldNamesHDR_Web = new K3.OeSalesOrderDAL().mstrFieldNamesHDR_Web;
        private string mstrFieldNamesDTL_Web = new K3.OeSalesOrderDAL().mstrFieldNamesDTL_Web;

        private K3.OeSalesOrderDAL.OrderInfo mcurOrder = new K3.OeSalesOrderDAL.OrderInfo();
        
        private string mstrWebInvNoFields = "fheadselfS0167";
        private string mstrWebDetailRecID = "FEntrySelfS0171";

        public enum FromType
        {
            SEOrder,
            ICSale,
            ICStockBill,
            ICStockBillEntry
        }
        public FromType mcurFromType = new FromType();

        private struct WebStatus
        {
            public string order_status;
            public string shipping_status;
            public string pay_status;
        }

        private enum WebStatusType
        {
            ICSales=0, //销售发票审核
            CancelICSales=1,//销售发票取消审核
            DelSEorder =2,    //删除订单
        }


        private bool UpdateSalesStatus(DBAccess dbK3Con, DBAccess dbWebCon, WebStatus webStatus, string strorder_sn)
        {
            ServerInfo K3Master = ServerInfo.GetK3MasterServer();

            string strSQL = "";
            string strPay_ID = CvtFunc.ToString(dbWebCon.GetValue("select pay_id from mary_order_info where order_sn='" + strorder_sn + "'"));
            strSQL = "select " + strPay_ID + ","+ strPay_ID.Length +" ";
            dbWebCon.ExecuteSql(strSQL);  
            if (strPay_ID.Trim() == "3")
            {
                webStatus.pay_status = "2";
            }
            else
            {
                webStatus.pay_status = "0";
            }
            if (K3Master.AcctType == "wh") webStatus.pay_status = "2";
            strSQL = @"update mary_order_info set order_status ='{0}'
                                                ,shipping_status='{1}'
                                                ,pay_status='{2}' where order_sn='{3}'";
            strSQL = string.Format(strSQL, webStatus.order_status, webStatus.shipping_status, webStatus.pay_status, strorder_sn);
            dbWebCon.ExecuteSql(strSQL);

            if (strPay_ID == "3") // 更新付款的时间
            {
                string strPayTime = CvtFunc.ToUnitStamp(DateTime.Now).ToString() ;
                strSQL = @"update mary_order_info set pay_time='{0}' where order_sn='{1}'";
                strSQL = string.Format(strSQL, strPayTime , strorder_sn);
                dbWebCon.ExecuteSql(strSQL);
            }
            return true;
        }

        public void Delete(DBAccess dbK3Con, DBAccess dbWebCon, string strKeyValue, Web.OeSalesOrderDAL.FromType mFromType)  //删除销售订单。
        {
            //如果K3中删除此销售订单，则需要改网站中的状态。
            string strSQL = "";
            try
            {
                if (mFromType == FromType.ICStockBillEntry) //删除红字出库单时，要删除网站上的负数行。
                {
                    UpdateSalesDetailByICStockBill(dbK3Con, dbWebCon, strKeyValue);
                }
                else if (mFromType == FromType.ICStockBill)
                {
                    //strKeyValue 是网站订单号
                    if (!CheckStockBillLog(dbK3Con, strKeyValue, "")) return;
                    string strOrder_sn = dbWebCon.GetValue("select order_sn from " + mstrOrderDtl_Web + " inner join "+ mstrOrderHdr_Web +" on "+ mstrOrderHdr_Web +".order_id = "+ mstrOrderDtl_Web +".order_id where k3stockbillfinterid='" + strKeyValue + "' ");
                    if (strOrder_sn == "") return;
                    #region 取得网站上的销售d   etail表，如果有<0的，就删除，重新从K3向网站上重新填写,k3stockbillfinterid是为了分开有退有多个销售单的情况（怕误删除的情况，多个红字对一个销售单）。
                    strSQL = "delete from " + mstrOrderDtl_Web + " where goods_number<0 and k3stockbillfinterid='" + strKeyValue + "' ";
                    dbWebCon.ExecuteSql(strSQL);

                    UpdateWebHdrByDetail(dbK3Con, dbWebCon, strOrder_sn);
                    #endregion
                }
                else
                {
                    if (!CheckSEORDERLog(dbK3Con, strKeyValue, "")) return;
                    string strorder_sn = strKeyValue;//dbK3Con.GetValue("select " + mstrWebInvNoFields + " from " + mstrOrderHdr_K3 + " where FinterID='" + strKeyValue + "'");
                    if (strorder_sn == "") return;
                    WebStatus webStatus = new WebStatus();
                    if (mFromType == FromType.SEOrder)
                    {
                        webStatus = GetcurWebStatus(WebStatusType.DelSEorder);
                        UpdateSalesStatus(dbK3Con, dbWebCon, webStatus, strorder_sn);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Debug("删除销售单，更新网站状态失败."+ ex.ToString());
            }
        }

        public void Add(DBAccess dbK3Con, DBAccess dbWebCon, string strKeyValue,Web.OeSalesOrderDAL.FromType  mFromType)
        {
           
        }

        public void Update(DBAccess dbK3Con, DBAccess dbWebCon, string strKeyValue, Web.OeSalesOrderDAL.FromType mFromType) // strKeyValue对应的是FinterID
        {
            if (mFromType == FromType.SEOrder)
            {
                UpdateSaleBySEOrder(dbK3Con, dbWebCon, strKeyValue, mFromType);
            }
            else if (mFromType == FromType.ICSale)
            {
                UpdateSalesDetailByICSales(dbK3Con, dbWebCon, strKeyValue);
            }
            else if (mFromType == FromType.ICStockBill)
            {
                UpdateSalesDetailByICStockBill(dbK3Con, dbWebCon, strKeyValue);
            }
        }

        //在销售单中直接更改
        //一般来说，只有在K3中改价格
        //这里是在K3销售单直接更改
        //FAuxQty
        //FAuxPrice

        private bool CheckSEORDERLog( DBAccess dbK3Con, string strFinterID,string strLogRecID)
        {
            //要注意因为  K3在写log的时候，是整个删除再加，所以会写add和delete的log
            //checklog查一下mlog 大于当前recid有没有同一finterid add的log,
            //如果还有记录就不是 Delete   = false
            //如果没有记录就是   Delete   = true

            if (dbK3Con.GetDataFirstRow("select * from  SEORDER where fheadselfS0167='" + strFinterID + "'") == null)
            {
                System.Threading.Thread.Sleep(100); 
                string strHdrFinterID = dbK3Con.GetValue("select finterid from seorder where  fheadselfS0167='" + strFinterID + "'");
                if (dbK3Con.GetDataFirstRow("select * from  SEORDEREntry where finterid='" + strHdrFinterID + "'") == null)
                {
                    if (strLogRecID == "") strLogRecID = dbK3Con.GetValue("select min(recid) from mlog where logtype='SEORDER'");
                    string strSQL = "select * from mLog where LogType in ('SEORDER','SEORDERENTRY') and KeyValue='" + strFinterID + "' and (LogStatus='0' or LogStatus='1') and RecID>'" + strLogRecID + "'";
                    DataRow drCheck = dbK3Con.GetDataFirstRow(strSQL);
                    if (drCheck == null)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        private bool CheckStockBillLog(DBAccess dbK3Con, string strFinterID, string strLogRecID)
        {
            //要注意因为  K3在写log的时候，是整个删除再加，所以会写add和delete的log
            //checklog查一下mlog 大于当前recid有没有同一finterid add的log,
            //如果还有记录就不是 Delete   = false
            //如果没有记录就是   Delete   = true
            if (strLogRecID == "") strLogRecID = dbK3Con.GetValue("select min(recid) from mlog where logtype='ICSTOCKBILL'");
            string strSQL = "select * from mLog where LogType in ('ICSTOCKBILL','ICSTOCKBILLENTRY') and KeyValue='" + strFinterID + "' and LogStatus='0' and RecID>'" + strLogRecID + "'";
            DataRow drCheck = dbK3Con.GetDataFirstRow(strSQL);
            if (drCheck == null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool UpdateSaleBySEOrder(DBAccess dbK3Con, DBAccess dbWebCon, string strKeyValue, Web.OeSalesOrderDAL.FromType mFromType) // strKeyValue对应的是FinterID
        {
            //要注意因为  K3在写log的时候，是整个删除再加，所以会写add和delete的log
            //checklog查一下mlog 大于当前recid有没有同一finterid add的log,有就不是delete

            //if (!CheckSEORDERLog(dbK3Con, strKeyValue, ""))    // 这里的RecID如何得到啊。 
            {
                string strSQL = "select * from " + mstrOrderHdr_K3 + " where FinterID='" + strKeyValue + "'";
                DataRow drK3Hdr = dbK3Con.GetDataFirstRow(strSQL);
                if (drK3Hdr != null)
                {
                    #region Set mcurOrderInfo
                    mcurOrder.BillNo_K3 = CvtFunc.ToString(drK3Hdr["FbillNo"]);
                    mcurOrder.BillNo_Web = CvtFunc.ToString(drK3Hdr[mstrWebInvNoFields]); //此处取WEB网站的单号。
                    mcurOrder.FInterID = CvtFunc.ToString(drK3Hdr["FInterID"]);
                    mcurOrder.CustID = CvtFunc.ToString(drK3Hdr["FCustID"]);
                    #endregion

                    UpdateSalesDetail(dbK3Con, dbWebCon, drK3Hdr);
                }
                return true;
            }
            return true;
        }

        private bool UpdateSalesDetail(DBAccess dbK3Con, DBAccess dbWebCon, DataRow drK3Hdr)
        {
            string strSQL = "";
            string strWebInvNo = CvtFunc.ToString(drK3Hdr[mstrWebInvNoFields]);
            double dblShippingAmt = 0;
            strSQL = " select B.*,C.f_137 from seorder A inner join seorderentry B on A.finterid=B.finterid";
            strSQL +=" inner join t_icitem C on b.fitemid=c.fitemid ";
            strSQL +=" where B.FinterID='"+ CvtFunc.ToString ( drK3Hdr["FinterID"])  +"'  ";
            DataTable dtDetail = dbK3Con.GetDataTable(strSQL) ;

            strSQL = " select sum(FAuxQty*FAuxPriceDiscount) as Amt from seorder A inner join seorderentry B on A.finterid=B.finterid";
            strSQL += " inner join t_icitem C on b.fitemid=c.fitemid ";
            strSQL += " where B.FinterID='" + CvtFunc.ToString(drK3Hdr["FinterID"]) + "'  ";
            strSQL += " and C.F_137='1'";            
            dblShippingAmt = CvtFunc.ToDouble ( dbK3Con.GetValue(strSQL));  

            foreach (DataRow drDetail in dtDetail.Rows)
            {
                if (CvtFunc.ToString(drDetail[mstrWebDetailRecID]) == "999" && CvtFunc.ToBoolean(drDetail["f_137"]))
                {
                    strSQL ="update "+ mstrOrderHdr_Web +" set shipping_fee='"+ dblShippingAmt +"' where order_sn='"+ strWebInvNo +"'";
                    dbWebCon.ExecuteSql(strSQL);
                }
                else
                {
                    if (CvtFunc.ToBoolean(dbWebCon.GetValue("select is_gift from  " + mstrOrderDtl_Web + " where rec_id='" + CvtFunc.ToString(drDetail[mstrWebDetailRecID]) + "'")))
                    {

                    }
                    else
                    {
                        strSQL = "update " + mstrOrderDtl_Web + " set send_number='" + CvtFunc.ToString(drDetail["FAuxQty"]) + "',goods_number='" + CvtFunc.ToString(drDetail["FAuxQty"]) + "', goods_price=" + CvtFunc.ToDouble(drDetail["FAuxPriceDiscount"]) + " where rec_id='" + CvtFunc.ToString(drDetail[mstrWebDetailRecID]) + "'";
                        dbWebCon.ExecuteSql(strSQL);
                    }
                }
            }
            UpdateWebHdrByDetail(dbK3Con, dbWebCon, strWebInvNo);  
            return true;
        }


        private bool UpdateSalesDetailByICSales(DBAccess dbK3Con, DBAccess dbWebCon, string strKeyValue) 
        {
            string strSQL="select * from icsale where FinterID='"+ strKeyValue +"'";
            DataRow drRow =dbK3Con.GetDataFirstRow( strSQL );
            if ( drRow ==null)
            {
                return false;
            }
            else
            {
                if ( string.IsNullOrEmpty ( CvtFunc.ToString(drRow["Fcheckerid"])) && !CvtFunc.ToBoolean(drRow["fstatus"]))  //取消审核
                {
                    return UpdateSalesDetailByICSales_Cancel(dbK3Con, dbWebCon, drRow);  
                }
                else if (!string.IsNullOrEmpty(CvtFunc.ToString(drRow["Fcheckerid"])) && CvtFunc.ToBoolean(drRow["fstatus"])) //审核
                {
                    return UpdateSalesDetailByICSales_Confim(dbK3Con, dbWebCon, drRow);
                }
                else
                {
                    return true;
                }
            }
        }

        //取消审核单据审核
        private bool UpdateSalesDetailByICSales_Cancel(DBAccess dbK3Con, DBAccess dbWebCon, DataRow drK3Hdr) 
        {
            string strSQL = "";
            #region 要取得销售回单
//            if (CheckTranType(dbK3Con, dbWebCon , CvtFunc.ToString(drK3Hdr["FinterID"]),"ICSALE") == "83")  //上级单据时发货通知单
//            {
//                strSQL = @"select top 1 {0},t3.FinterID from icsale t1
//	            inner join icsaleentry t2 on t1.finterid=t2.finterid
//	            inner join icstockbillentry t3 on t2.FSourceInterId=t3.finterid
//	            inner join seoutstockentry t4 on t3.FSourceInterId=t4.finterid
//	            inner join seorderentry t5 on t4.FSourceInterId=t5.finterid
//	            inner join seorder t6 on t5.finterid=t6.finterid
//	            where t1.finterid='" + CvtFunc.ToString(drK3Hdr["FinterID"]) + "' ";
//            }
//            else  //上级单据是销售
//            {
//                strSQL = @"select top 1 {0},t3.FinterID from icsale t1
//	            inner join icsaleentry t2 on t1.finterid=t2.finterid
//	            inner join icstockbillentry t3 on t2.FSourceInterId=t3.finterid
//	            inner join seorderentry t5 on t3.FSourceInterId=t5.finterid
//	            inner join seorder t6 on t5.finterid=t6.finterid
//	            where t1.finterid='" + CvtFunc.ToString(drK3Hdr["FinterID"]) + "'";
//            }
//          strSQL = string.Format(strSQL, mstrWebInvNoFields);
            string strWebInvNoFieldName = "fheadselfI0452";
            strSQL = " select t1."+ strWebInvNoFieldName +", FOrderInterID,FOrderBillNo from icsale t1 ";
            strSQL +=" inner join icsaleentry t2 on t1.finterid=t2.finterid ";
            strSQL +=" where t2.finterid='" + CvtFunc.ToString(drK3Hdr["FinterID"]) + "'";    
            DataRow drK3StockBill = dbK3Con.GetDataFirstRow(strSQL);
            if (drK3StockBill == null) return true;//如果没有找到则退出，可能说明不是网站数据。

            string strWebInvNo = CvtFunc.ToString(drK3StockBill[strWebInvNoFieldName]);
            if (strWebInvNo == "") return false;
            #endregion

            #region 更新网站的mary_order_info的状态
            WebStatus curWebStatus = new WebStatus();
            curWebStatus = GetcurWebStatus(WebStatusType.CancelICSales);
            UpdateSalesStatus(dbK3Con, dbWebCon, curWebStatus, strWebInvNo);
            #endregion
            return true;
        }

        //由于开发票的时候，可以更改价格和数量，此时要更新网站的销售订单,此处是审核单据
        private bool UpdateSalesDetailByICSales_Confim(DBAccess dbK3Con, DBAccess dbWebCon, DataRow drK3Hdr)
        {
            string strSQL = "";
         
            #region 要取得销售回单
//            if (CheckTranType(dbK3Con, dbWebCon, CvtFunc.ToString( drK3Hdr["FinterID"]),"ICSALE") == "83")  //上级单据时发货通知单
//            {
//                strSQL = @"select top 1 {0},t3.FinterID from icsale t1
//	            inner join icsaleentry t2 on t1.finterid=t2.finterid
//	            inner join icstockbillentry t3 on t3.FSourceInterId=t2.finterid
//	            inner join seoutstockentry t4 on t3.FSourceInterId=t4.finterid
//	            inner join seorderentry t5 on t4.FSourceInterId=t5.finterid
//	            inner join seorder t6 on t5.finterid=t6.finterid
//	            where t1.finterid='" + CvtFunc.ToString(drK3Hdr["FinterID"]) + "' ";
//            }
//            else  //上级单据是销售
//            {
//                strSQL = @"select top 1 {0},t3.FinterID from icsale t1
//	            inner join icsaleentry t2 on t1.finterid=t2.finterid
//	            inner join icstockbillentry t3 on t3.FSourceInterId=t2.finterid
//	            inner join seorderentry t5 on t3.FSourceInterId=t5.finterid
//	            inner join seorder t6 on t5.finterid=t6.finterid
//	            where t1.finterid='" + CvtFunc.ToString(drK3Hdr["FinterID"]) + "'";
//            }
//            strSQL = string.Format(strSQL, mstrWebInvNoFields);
            string strWebInvNoFieldName = "fheadselfI0452";
            strSQL = " select t1." + strWebInvNoFieldName + ", FOrderInterID,FOrderBillNo from icsale t1 ";
            strSQL += " inner join icsaleentry t2 on t1.finterid=t2.finterid ";
            strSQL += " where t2.finterid='" + CvtFunc.ToString(drK3Hdr["FinterID"]) + "'";
            DataRow drK3StockBill = dbK3Con.GetDataFirstRow(strSQL);
            if (drK3StockBill == null) return true;//如果没有找到则退出，可能说明不是网站数据。

            string strWebInvNo = CvtFunc.ToString(drK3StockBill[strWebInvNoFieldName]);
            if (strWebInvNo == "") return false; ;//如果没有找到则退出，可能说明不是网站数据。                         
            #endregion
                        
            #region 取得网站上的销售detail表，重新从K3向网站上重新填写

            strSQL = " select sum(FAuxQty*FAuxPriceDiscount) as Amt from icsale A inner join icsaleentry B on A.finterid=B.finterid";
            strSQL += " inner join t_icitem C on b.fitemid=c.fitemid ";
            strSQL += " where B.FinterID='" + CvtFunc.ToString(drK3Hdr["FinterID"]) + "'  ";
            strSQL += " and C.F_137='1'";
            double dblShippingAmt = CvtFunc.ToDouble(dbK3Con.GetValue(strSQL));  

            string strWebHdrRec_ID = dbWebCon.GetValue("select order_id from "+ mstrOrderHdr_Web +" where order_sn='"+ strWebInvNo +"'");
            strSQL ="  select A.*,B."+ mstrWebDetailRecID +" from icsaleentry A ";
            strSQL += " inner join seorderentry B on A.FOrderInterID=B.FinterID and A.FOrderEntryID=B.FEntryID";
            strSQL += " where A.finterid='" + CvtFunc.ToString(drK3Hdr["FinterID"]) + "' and A.Fqty>0";
            DataTable dtK3Dtl = dbK3Con.GetDataTable(strSQL);  
            foreach (DataRow drRow in dtK3Dtl.Rows)
            {
                strSQL = "select * from " + mstrOrderDtl_Web + " where rec_id='"+ CvtFunc.ToString( drRow[mstrWebDetailRecID]) +"'";
                DataRow drWebDtl = dbWebCon.GetDataFirstRow(strSQL);
                if (drWebDtl != null)
                {
                    strSQL = "update " + mstrOrderDtl_Web + " set send_number='" + CvtFunc.ToString(drRow["FAuxQty"]) + "', goods_number='" + CvtFunc.ToString(drRow["FAuxQty"]) + "' , goods_price=" + CvtFunc.ToDouble(drRow["FAuxPriceDiscount"]) + " where rec_id='" + CvtFunc.ToString(drRow[mstrWebDetailRecID]) + "'";
                    dbWebCon.ExecuteSql(strSQL); 
                }
            }
            strSQL ="update "+ mstrOrderHdr_Web +" set shipping_fee ='"+ dblShippingAmt +"' where order_sn='"+ strWebInvNo +"'";
            dbWebCon.ExecuteSql(strSQL); 
            UpdateWebHdrByDetail(dbK3Con, dbWebCon, strWebInvNo);  //更新网站mary_order_info中的金额
            #endregion


            #region 更新网站的mary_order_info的状态
            WebStatus curWebStatus = new WebStatus();
            curWebStatus = GetcurWebStatus(WebStatusType.ICSales);
            UpdateSalesStatus(dbK3Con, dbWebCon, curWebStatus, strWebInvNo);

            #endregion

            return true;
        }

        private WebStatus GetcurWebStatus(WebStatusType webStautsType)
        {
            WebStatus curWebStatus = new WebStatus();
            if (webStautsType== WebStatusType.ICSales)   //审核销售发票
            {
                curWebStatus.order_status = "5";
                curWebStatus.shipping_status = "2";
                curWebStatus.pay_status = "2";    
            }
            else if (webStautsType == WebStatusType.DelSEorder) //删除销售订单
            {
                curWebStatus.order_status = "2";
                curWebStatus.shipping_status = "0";
                curWebStatus.pay_status = "0"; 
            }
            else if (webStautsType == WebStatusType.CancelICSales) //取消发票审核
            {
                curWebStatus.order_status = "1";  
                curWebStatus.shipping_status = "2";
                curWebStatus.pay_status = "2"; 
            }
            return curWebStatus;
        }

        private string CheckTranType(DBAccess dbK3Con, DBAccess dbWebCon, string strFinterID,string strType)
        {
            //select top 1 t3.FSourceTranType from icsale t1
            //inner join icsaleentry t2 on t1.finterid=t2.finterid
            //inner join icstockbillentry t3 on t2.FSourceInterId=t3.finterid
            //where t1.fbillno='ZSEFP022334' 
            string strSQL = @"select top 1 t3.FSourceTranType from icsale t1
                        inner join icsaleentry t2 on t1.finterid=t2.finterid
                        inner join icstockbillentry t3 on t3.FSourceInterId=t2.finterid";
            if (strType == "ICSALE")
            {
                strSQL +=" where t2.finterid='" + strFinterID + "' ";
            }
            else if ( strType =="ICSTOCKBILL")
            {
                strSQL +=" where t3.finterid='" + strFinterID + "' ";
            }
            DataRow drRow = dbK3Con.GetDataFirstRow(strSQL);
            if (drRow == null)
            {
                return "";
            }
            if (CvtFunc.ToString(drRow["FSourceTranType"]) == "83")
            {
                return "83";
            }
            else
            {
                return "";
            }            
        }

        //由红字出库单来更新网站销售单
        //此时的K3Hdr是来自icstockbill
        //cstockbillentry.FSourceTranType=83代表是代表他的上级单据时发货通知单
        //否则就代表这个单子的上级单据是销售
        //select top 1 t3.FSourceTranType from icsale t1
        //inner join icsaleentry t2 on t1.finterid=t2.finterid
        //inner join icstockbillentry t3 on t2.FSourceInterId=t3.finterid
        //where t1.fbillno='ZSEFP022334' 
        private bool UpdateSalesDetailByICStockBill(DBAccess dbK3Con, DBAccess dbWebCon, string strFinterID)
        {
            string strSQL="";
            string strHdr_TableName = "icstockbill";
            string strDtl_TableName = "icstockbillentry";
//            if (CheckTranType(dbK3Con, dbWebCon, strFinterID, "ICSTOCKBILL") == "83")  //上级单据时发货通知单
//            {
//                strSQL = @"select top 1 {0},t3.FinterID,t3.FUnitID from icsale t1
//	            inner join icsaleentry t2 on t1.finterid=t2.finterid
//	            inner join icstockbillentry t3 on t3.FSourceInterId=t2.finterid
//	            inner join seoutstockentry t4 on t3.FSourceInterId=t4.finterid
//	            inner join seorderentry t5 on t4.FSourceInterId=t5.finterid
//	            inner join seorder t6 on t5.finterid=t6.finterid
//	            where t3.finterid='" + strFinterID + "' ";
//            }
//            else  //上级单据是销售
//            {
//                strSQL = @"select top 1 {0},t3.FinterID,t3.FUnitID from icsale t1
//	            inner join icsaleentry t2 on t1.finterid=t2.finterid
//	            inner join icstockbillentry t3 on t3.FSourceInterId=t2.finterid
//	            inner join seorderentry t5 on t3.FSourceInterId=t5.finterid
//	            inner join seorder t6 on t5.finterid=t6.finterid
//	            where t3.finterid='" + strFinterID + "'";
//            }
//            strSQL = string.Format(strSQL, mstrWebInvNoFields);
            string strWebInvNoFiledName = "fheadselfB0159";
            strSQL = "select A."+ strWebInvNoFiledName +",B.* from icstockbill A inner join icstockbillentry B on A.FinterID=B.FinterID and A.FinterID='"+ strFinterID +"'";
            DataRow drK3StockBill = dbK3Con.GetDataFirstRow(strSQL);
            if (drK3StockBill == null) return true;//如果没有找到则退出，可能说明不是网站数据。

            string strWebInvNo = CvtFunc.ToString(drK3StockBill[strWebInvNoFiledName]); 
            if (strWebInvNo == "") return true ; //如果没有找到则退出，可能说明不是网站数据。
            string strK3StockBillFinterID = CvtFunc.ToString(drK3StockBill["FinterID"]);

            //向K3追加退货单
            strSQL = "select * from " + strDtl_TableName + " where FInterID='" + strK3StockBillFinterID + "' and FQty<0";
            DataTable dtK3Dtl = dbK3Con.GetDataTable(strSQL); 
            if (dtK3Dtl.Rows.Count <= 0) return true;//如果没有红字退货，退出。

            string strWebOrder_ID =dbWebCon.GetValue("select order_id from "+ mstrOrderHdr_Web +" where order_sn='"+ strWebInvNo +"'"); 
            if (strWebOrder_ID =="") return false;

            #region 取得网站上的销售detail表，如果有<0的，就删除，重新从K3向网站上重新填写,k3stockbillfinterid是为了分开有退有多个销售单的情况（怕误删除的情况，多个红字对一个销售单）。
            strSQL = "delete from " + mstrOrderDtl_Web + " where order_id='" + strWebOrder_ID + "' and goods_number<0 and k3stockbillfinterid='" + strK3StockBillFinterID + "' ";
            dbWebCon.ExecuteSql(strSQL);            
            #endregion
            

            #region 取得K3Master的连接
            ServerInfo K3Master = ServerInfo.GetK3MasterServer();
            DBAccess dbK3Master = new DBAccess(K3Master);

            #endregion
            #region 由K3的Detail向网站上填负数的Detail          
            foreach (DataRow drRow in dtK3Dtl.Rows)
            {
               
                strSQL =" select * from t_icitem where fitemid='"+ CvtFunc.ToString ( drRow["FItemID"] ) +"' and F_137='1'";
                DataRow drIsShipFee = dbK3Con.GetDataFirstRow(strSQL);
                if (drIsShipFee == null)  //不是运费
                {
                    strSQL = "select * from mary_order_goods where order_id=0";
                    DataRow drNewWeb = dbWebCon.GetDataTable(strSQL).NewRow();

                    string strMasterItemID = new K3.ImInvMasterDAL().GetOrgMapKeyValue(dbK3Master, dbK3Con, CvtFunc.ToString(drRow["FItemID"]));
                    drNewWeb["order_id"] = CvtFunc.ToLong(strWebOrder_ID);
                    drNewWeb["FItemID"] = CvtFunc.ToLong(strMasterItemID);
                    drNewWeb["goods_id"] = CvtFunc.ToLong(dbWebCon.GetValue("select goods_id from mary_goods where FItemID='" + strMasterItemID + "'"));
                    drNewWeb["goods_name"] = dbK3Con.GetValue("select fname from t_icitem where fitemid='" + CvtFunc.ToString(drRow["FItemID"]) + "'");
                    drNewWeb["goods_sn"] = dbK3Con.GetValue("select f_125 from t_icitem where fitemid='" + CvtFunc.ToString(drRow["FItemID"]) + "'");
                    drNewWeb["goods_number"] = CvtFunc.ToDouble(drRow["FAuxQty"]);
                    drNewWeb["goods_unit"] = dbK3Con.GetValue("select FName from t_measureunit where FMeasureUnitID='" + CvtFunc.ToString(drRow["FUnitID"]) + "'");
                    //drNewWeb["market_price"]= CvtFunc.ToDouble (drRow["FAuxPrice"]); 
                    drNewWeb["goods_price"] = CvtFunc.ToDouble(drRow["FconsignPrice"]);
                    drNewWeb["send_number"] = CvtFunc.ToDouble(drRow["FAuxQty"]);
                    drNewWeb["k3stockbillfinterid"] = CvtFunc.ToInt(drRow["finterid"]);
                    //drNewWeb["goods_color"] = CvtFunc.ToInt(drRow["FentrySelfB0158"]);
                    KeyValuePair<string, IDataParameter[]> kvp = dbWebCon.CreateParamSql(mstrFieldNamesDTL_Web, mstrOrderDtl_Web, drNewWeb, LogStatus.Add, "rec_id");
                    dbWebCon.ExecuteSql(kvp.Key, kvp.Value);
                }
                else
                {
                    double dblShippingAmt = 0;
                    dblShippingAmt = CvtFunc.ToDouble(drRow["FconsignPrice"]) * CvtFunc.ToDouble(drRow["FAuxQty"]);
                    strSQL = "update " + mstrOrderHdr_Web + " set shipping_fee =shipping_fee +'" + dblShippingAmt + "' where order_sn='" + strWebInvNo + "'";
                    dbWebCon.ExecuteSql(strSQL);
                }
            }
            UpdateWebHdrByDetail(dbK3Con,dbWebCon, strWebInvNo);  
            #endregion
            return true;
        }

        private void SetWebDataRowByK3SOOrderEntry(DBAccess dbK3Con, DBAccess dbWebCon, DataRow drK3Hdr)
        {

        }

        private bool UpdateWebHdrByDetail(DBAccess dbK3Con, DBAccess dbWebCon, string strOrder_sn)//更新网站数据库的表头金额
        {
            double dblAmt = 0;
            double dblPrice = 0;
            double dblQty = 0;
            string strSQL = "";           
            strSQL = "select A.* from " + mstrOrderDtl_Web + " A inner join " + mstrOrderHdr_Web + " B on A.order_id=B.order_id where B.order_sn='" + strOrder_sn + "'";
            DataTable dtOrderDetail = dbWebCon.GetDataTable(strSQL);
            foreach (DataRow drRow in dtOrderDetail.Rows)
            {
                dblPrice = CvtFunc.ToDouble(drRow["goods_price"]);
                dblQty = CvtFunc.ToDouble(drRow["send_number"]);
                dblAmt += dblPrice * dblQty;
            }
            strSQL = "update mary_order_info set goods_amount='" + dblAmt + "', order_amount=" + dblAmt + "+shipping_fee+insure_fee+pay_fee+pack_fee+card_fee+separate_fee where order_sn='" + strOrder_sn + "'";
            dbWebCon.ExecuteSql(strSQL);            
            return true;
        }

    }
}
